package com.blue.base.common.utils.encrypt;

import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 加密工具类
 *
 * @author liulei
 * @version 1.0
 */
public class EncryptUtil {

    private static final String BASE = "abcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 获取密码盐
     */
    public static String getRandomSalt(int length) {
        return getRandomString(length);
    }

    /**
     * md5加密，带盐值
     */
    public static String md5Encrypt(String password, String salt) {
        if (StringUtils.isEmpty(salt) || StringUtils.isEmpty(salt)) {
            throw new IllegalArgumentException("密码或盐为空！");
        } else {
            return encrypt(password + salt);
        }
    }

    /**
     * 获取随机字符,自定义长度
     */
    private static String getRandomString(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(BASE.length());
            sb.append(BASE.charAt(number));
        }
        return sb.toString();
    }

    private static String encrypt(String source) {
        return encodeMd5(source.getBytes());
    }

    private static String encodeMd5(byte[] source) {
        try {
            return encodeHex(MessageDigest.getInstance("MD5").digest(source));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    private static String encodeHex(byte[] bytes) {
        StringBuffer buffer = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buffer.append("0");
            }
            buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buffer.toString();
    }

}
